import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

# 读取数据
df = pd.read_excel(r"water_tu/IS on CH4.xlsx", sheet_name="Daily")
X = df[['IS_Chla', 'IS_DOC']]
Y = df['CH4']

# 使用3次多项式回归
degree = 3
poly = PolynomialFeatures(degree)
X_poly = poly.fit_transform(X)

# 拟合模型
model = LinearRegression()
model.fit(X_poly, Y)

# 获取系数
coefficients = model.coef_
print(f'Coefficients: {coefficients}')


# 创建偏导数计算函数
def calculate_partial_derivatives(X, coefficients, degree=3):
    # 提取输入变量
    Chla = X[:, 1]  # 叶绿素a
    DOC = X[:, 2]  # DOC

    # 对Chla和DOC求偏导数
    # 一次项：X[:, 1]代表Chla, X[:, 2]代表DOC
    # 二次项：X[:, 3]是Chla^2, X[:, 4]是Chla*DOC, X[:, 5]是DOC^2
    partial_Chla = coefficients[1] + 2 * coefficients[3] * Chla + coefficients[4] * DOC
    partial_DOC = coefficients[2] + 2 * coefficients[5] * DOC + coefficients[4] * Chla

    return partial_Chla, partial_DOC


# 计算偏导数
partial_Chla, partial_DOC = calculate_partial_derivatives(X_poly, coefficients)

# 输出结果
df['Partial_Chla'] = partial_Chla
df['Partial_DOC'] = partial_DOC

# 显示结果
df[['IS_Chla', 'IS_DOC', 'Partial_Chla', 'Partial_DOC']].head()

# 可视化叶绿素a和DOC的偏导数变化
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))

# 叶绿素a的偏导数变化
plt.subplot(211)
plt.plot(df['IS_Chla'], df['Partial_Chla'], label='Partial Derivative of CH4 wrt Chla', color='blue')
plt.title('Partial Derivative of CH4 with respect to Chla')
plt.xlabel('Chlorophyll-a')
plt.ylabel('Partial Derivative')

# DOC的偏导数变化
plt.subplot(212)
plt.plot(df['IS_DOC'], df['Partial_DOC'], label='Partial Derivative of CH4 wrt DOC', color='orange')
plt.title('Partial Derivative of CH4 with respect to DOC')
plt.xlabel('DOC')
plt.ylabel('Partial Derivative')

plt.tight_layout()
plt.show()
